package com.samnative.pineapple.utils;

import android.app.AppOpsManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.shashank.sony.fancytoastlib.FancyToast;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 判断通知权限是否关闭的工具
 * Created by Administrator on 2019/7/2.
 */

public class NoticePermissUtil {

    public static final int REQUEST_SETTING_NOTIFICATION = 2002;

    /**
     * 统一判断
     *
     * @param context
     * @return
     */
    public static boolean areNotificationsEnabled(Context context) {
        NotificationManagerCompat.from(context).areNotificationsEnabled();
        if (Build.VERSION.SDK_INT < 19) {
            return true;
        }
        if (Build.VERSION.SDK_INT < 26) {
            LogUtils.e("19*" + isEnableV19(context));
            return isEnableV19(context);
        } else {
            LogUtils.e("26=" + isEnableV26(context));
            return isEnableV26(context);
        }
    }


    /**
     * 判断API19-25
     *
     * @param context
     * @return
     */
    private static boolean isEnableV19(Context context) {
        final String CHECK_OP_NO_THROW = "checkOpNoThrow";
        final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null; /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);
            return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException e) {
        } catch (NoSuchFieldException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 判断API26及以上
     *
     * @param context
     * @return
     */
    private static boolean isEnableV26(Context context) {
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        try {
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            Method sServiceField = notificationManager.getClass().getDeclaredMethod("getService");
            sServiceField.setAccessible(true);
            Object sService = sServiceField.invoke(notificationManager);

            Method method = sService.getClass().getDeclaredMethod("areNotificationsEnabledForPackage"
                    , String.class, Integer.TYPE);
            method.setAccessible(true);
            return (boolean) method.invoke(sService, pkg, uid);
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 弹窗提示,并跳转至相关设置页面
     *
     * @param activity
     */
    public static void gotoNotificationSetting(AppCompatActivity activity) {
        MessageDialog.show(activity, "通知权限", "需要打开允许通知才能收到推送消息,是否前往设置", "确定", "取消").setOnOkButtonClickListener(
                new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {

                        ApplicationInfo appInfo = activity.getApplicationInfo();
                        String pkg = activity.getApplicationContext().getPackageName();
                        int uid = appInfo.uid;
                        try {
                            if (Build.VERSION.SDK_INT >= 21) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                                //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                                intent.putExtra(Settings.EXTRA_APP_PACKAGE, pkg);
                                intent.putExtra(Settings.EXTRA_CHANNEL_ID, uid);
                                //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
                                intent.putExtra("app_package", pkg);
                                intent.putExtra("app_uid", uid);
                                activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
                            } else if (Build.VERSION.SDK_INT == 19) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setData(Uri.parse("package:" + pkg));
                                activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
                            } else {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
                            }
                        } catch (Exception e) {

                            FancyToast.showToast(activity,"跳转失败,请手动前往手机设置里打开通知权限", FancyToast.WARNING,false);
                        }


                        return false;
                    }
                });


    }

}
